<?php

if (!function_exists('path_info')) {
    function path_info($filepath, $flags = null)
    {
        $newPath = strtr($filepath, ['\\' => '/']);
        $basename = ltrim(substr($newPath, strrpos($newPath, '/')), "/");
        $extension = substr(strrchr($newPath, '.'), 1);
        $filename = ltrim(substr($basename, 0, strrpos($basename, '.')), "/");
        $dirname = rtrim(substr($filepath, 0, strrpos($filepath, $basename) - 1));
        switch ($flags) {
            case 1:
                return $dirname;
            case 2:
                return $basename;
            case 4:
                return $extension;
            case 8:
                return $filename;
            default:
                return [
                    'dirname'   => $dirname,
                    'basename'  => $basename,
                    'extension' => $extension,
                    'filename'  => $filename,
                ];
        }
    }
}
//用户分类
if (!function_exists('admin_user_cate')) {
    function admin_user_cate(): array
    {
        return [1 => '系统管理员', 2 => '部门管理员', 3 => '普通用户'];
    }
}

if (!function_exists('patent_type_select_option')) {
    function patent_type_select_option(): array
    {
        return [
            1 => '发明专利',
            2 => '实用新型',
            3 => '外观设计',
            4 => 'PCT申请',
            5 => '国外专利'
        ];
    }
}

if (!function_exists('patent_legal_status')) {
    function patent_legal_status()
    {
        return collect([
            '在审' => '在审',
            '无效' => '无效',
            '有效' => '有效',
            '其他' => '其他',
        ]);
    }
}

if (!function_exists('patent_fee_type')) {
    function patent_fee_type()
    {
        return collect([
            1 => '年费',
            2 => '滞纳金',
            3 => '恢复费',
            4 => '其它'
        ]);
    }
}

if (!function_exists('admin_route')) {
    //科研处端路由
    function admin_route($name, $parameters = [], $absolute = true)
    {
        $prefix = config('admin.route.prefix');
        if ($prefix) {
            return route($prefix . '.' . $name, $parameters, $absolute);
        }
        return route($name, $parameters, $absolute);
    }
}

if (!function_exists('common_route')) {
    function common_route($name, $parameters = [], $absolute = true, $prefix = '')
    {
        if ($prefix) {
            return route($prefix . '.' . $name, $parameters, $absolute);
        }
        return route($name, $parameters, $absolute);
    }
}


//教师端路由
if (!function_exists('user_route')) {
    function user_route($name, $parameters = [], $absolute = true): string
    {
        return common_route($name, $parameters, $absolute, config('inventor.route.prefix'));
    }
}

if (!function_exists('dept_route')) {
    //学院端
    function dept_route($name, $parameters = [], $absolute = true)
    {
        return common_route($name, $parameters, $absolute, config('department.route.prefix'));
    }
}

if (!function_exists('using_label')) {
    function using_label(array $names, $labels = [], $default_label = '')
    {
        return collect($names)->map(function ($value, $key) use ($labels, $default_label) {
            $label = data_get($labels, $key, $default_label);
            if ($value && $label) {
                return '<span class="label label-' . $labels[$key] . '">' . $value . '</span>';
            }
            return $value ?: '';
        })->all();
    }
}

if (!function_exists('download_a')) {
    function download_a($path, $name)
    {
        return '<a download="下载" target="_blank" href="' . $path . '">' . $name . '</a>';
    }
}
if (!function_exists('patent_sn_match')) {
    function patent_sn_match($sn)
    {
        $sn = strtoupper($sn);
        if (!preg_match('/(^\d{8}[0-9Xx]$)|(^\d{12}[0-9Xx]$)/', $sn)) {
            return '';
        }
        $length = strlen($sn);
        $multiple = [2, 3, 4, 5, 6, 7, 8, 9, 2, 3, 4, 5];
        $a = 0;
        for ($i = 0; $i < $length - 1; $i++) {
            $a = $a + substr($sn, $i, 1) * $multiple[$i];
        }
        $last_str = substr($sn, $length - 1, 1);
        $b = $a % 11;
        if ($b == $last_str || ($b > 9 && $last_str == 'X')) {
            return $sn;
        }
        return '';
    }
}
if (!function_exists('china_patent_sn')) {
    function china_patent_sn($sn)
    {
        $sn = strtoupper(strtr($sn, ['.' => '', ' ' => '']));
        $length = strlen($sn);
        if (!in_array($length, [13, 15])) {
            return '';
        }
        if ($length == 15) {
            $a = substr($sn, 0, 2);
            if (!in_array($a, ['ZL', 'CN'])) {
                return '';
            }
            $sn = substr($sn, 2);
        }
        return patent_sn_match($sn);
    }
}
if (!function_exists('check_patent_sn_type')) {
    function check_patent_sn_type($sn, $type): bool
    {
        $length = strlen($sn);
        if ($length == 13) {
            return substr($sn, 4, 1) == $type;
        } elseif ($length == 9) {
            return substr($sn, 2, 1) == $type;
        }
        return false;
    }
}


if (!function_exists('project_level_options')) {
    function project_level_options()
    {
        return collect([
            1 => '国家级',
            2 => '省厅级',
            3 => '市级',
            4 => '校级',
            5 => '其它',
        ])->all();
    }
}

if (!function_exists('project_member_type_options')) {
    function project_member_type_options()
    {
        return collect([
            '教师' => '教师',
            '学生' => '学生',
            '校外' => '校外'
        ])->all();
    }
}


if (!function_exists('project_edu_degree_options')) {
    function project_edu_degree_options()
    {
        return collect([
            100 => '名誉博士',
            1   => '博士',
            2   => '硕士',
            3   => '学士',
            99  => '无'
        ])->all();
    }
}
if (!function_exists('project_bear_type_options')) {
    function project_bear_type_options()
    {
        return collect([
            1 => '负责人',
            2 => '主要参与人',
            3 => '参与人',
        ])->all();
    }
}

if (!function_exists('project_member_identity_options')) {
    function project_member_identity_options()
    {
        return collect([
            '负责人'     => '负责人',
            '主要参与人' => '主要参与人',
            '参与人'     => '参与人',
        ])->all();
    }
}


if (!function_exists('project_subject_type_options')) {
    function project_subject_type_options()
    {
        return [
            1 => '科技类',
            2 => '社科类'
        ];
    }
}

if (!function_exists('project_status_options')) {
    function project_status_options()
    {
        return ['进行', '完成', '暂停', '撤销'];
    }
}

if (!function_exists('department_options')) {
    function department_options()
    {
        return \App\Models\Department::pluck('name', 'id')->toArray();
    }
}

if (!function_exists('grid_column_tip')) {
    function grid_column_tip($title, $placement = 'left')
    {
        if (!$title) return '';
        return <<<HTML
<span data-toggle="tooltip" data-placement="{$placement}" data-html="true" data-title="{$title}"><i class="fa fa-question-circle"></i></span>
HTML;
    }
}
if (!function_exists('dept_check_review')) {
    function dept_check_review(): bool
    {
        return config('department.enable') && config('department.review');
    }
}

function org_name()
{
    return config('app.org_name');
}


function modal_expert_detail($model)
{
    return \Encore\Admin\Facades\Admin::show($model, function (\Encore\Admin\Show $show) {
        $show->panel()->view('show.tab-panel');
        $show->field('name', __('姓名'));
        $show->field('mobile', __('联系电话'));
        $show->field('major', '专业领域');
        $show->field('company', '单位');
    });
}

function project_contract_type_options()
{
    return \App\ContractType::query()->pluck('name', 'name');
}

function department_select_options()
{
    return \App\Models\Department::query()->pluck('name', 'id')->toArray();
}

function project_technical_field_select_options(): array
{
    return \App\TechnicalField::query()->pluck('name', 'name')->toArray();
}

function response_preview($content, $name)
{
    $extension = strtolower(pathinfo($name, PATHINFO_EXTENSION));
    if ($extension == 'pdf') {
        return response($content, 200, [
            'Content-Type' => 'application/pdf',
        ]);
    } elseif (in_array($extension, ['jpg', 'png', 'jpeg', 'gif'])) {
        return response($content, 200, [
            'Content-Type' => 'image/png',
        ]);
    } else {
        return response_stream_download($content, $name);
    }
}


if (!function_exists('response_stream_download')) {
    function response_stream_download($output, $filename): \Symfony\Component\HttpFoundation\StreamedResponse
    {
        return response()->streamDownload(function () use ($output) {
            echo $output;
        }, strtr($filename, ['/' => '／', '\\' => '＼', '?' => '？', '*' => '×', '"' => '“', ':' => '：']));
    }
}
if (!function_exists('storage_stream_download')) {
    function storage_stream_download(\Illuminate\Filesystem\FilesystemAdapter $storage, $path, $filename = null): \Symfony\Component\HttpFoundation\StreamedResponse
    {
        return response()->stream(function () use ($storage, $path, $filename) {
            $stream = $storage->readStream($path);
            fpassthru($stream);
            if (is_resource($stream)) {
                fclose($stream);
            }
        }, 200, [
            'Cache-Control'       => 'must-revalidate, post-check=0, pre-check=0',
            'Content-Type'        => $storage->mimeType($path),
            'Content-Length'      => $storage->size($path),
            'Content-Disposition' => 'attachment; filename="' . $filename . '"',
            'Pragma'              => 'public',
        ]);
    }
}

if (!function_exists('storage_stream_preview')) {
    function storage_stream_preview(\Illuminate\Filesystem\FilesystemAdapter $storage, $path): \Symfony\Component\HttpFoundation\StreamedResponse
    {
        return response()->stream(function () use ($storage, $path) {
            $stream = $storage->readStream($path);
            fpassthru($stream);
            if (is_resource($stream)) {
                fclose($stream);
            }
        }, 200, [
            'Cache-Control'  => 'must-revalidate, post-check=0, pre-check=0',
            'Content-Type'   => $storage->mimeType($path),
            'Content-Length' => $storage->size($path),
            'Pragma'         => 'public',
        ]);
    }
}


if (!function_exists('policy_check')) {
    function policy_check($ability, $arguments = []): bool
    {
        return \Illuminate\Support\Facades\Gate::check($ability, $arguments);
    }
}

function cache_grid_column(\Encore\Admin\Grid $grid)
{
    $grid->rendering(function (Encore\Admin\Grid $grid) {
        $user = \Encore\Admin\Facades\Admin::user();
        $key = 'cache_grid_column-' . md5($user['id'] . '-' . request()->path());
        $_columns_ = request()->get('_columns_');
        if (!$_columns_) {
            $_columns_ = \Illuminate\Support\Facades\Cache::get($key);
        } else {
            \Illuminate\Support\Facades\Cache::forget($key);
            \Illuminate\Support\Facades\Cache::forever($key, request()->get('_columns_'));
        }
        if ($_columns_) {
            $grid->hiddenColumns = array_merge($grid->hiddenColumns, $grid->getDefaultVisibleColumnNames());
            foreach ($grid->hiddenColumns as $key => $column) {
                if (strstr($_columns_, $column)) {
                    unset($grid->hiddenColumns[$key]);
                }
            }
        }
    });
}

function tree_review_status(\Encore\Admin\Grid $grid)
{
    $admin_review_name = \App\Setting::getReviewName(1);
    $dept_review_name = \App\Setting::getReviewName(2);
    return $grid->column('review_status', __('审批状态'))->display(function ($value) use ($admin_review_name, $dept_review_name) {
        if ($value) {
            return data_get([
                1 => '<span class="label label-success">' . $admin_review_name . '-通过</span>',
                2 => '<span class="label label-default">' . $admin_review_name . '-未通过</span>',
                3 => '<span class="label label-default">' . $admin_review_name . '-退回修改</span>',
            ], $value);
        } else {
            return data_get([
                '<span class="label label-warning">' . $dept_review_name . '-待处理</span>',
                '<span class="label label-warning">' . $admin_review_name . '-待处理</span>',
                '<span class="label label-default">' . $dept_review_name . '-未通过</span>',
            ], $this->dept_review_status);
        }
    })->tooltip(function ($model) {
        return in_array($model->review_status, [2, 3]) || $model->dept_review_status == 2 ? $model->review_remark : '';
    });
}

function select_sale_type_options(): array
{
    return [
        '自行实施' => '自行实施',
        '转让'     => '转让',
        '许可'     => '许可',
        '作价入股' => '作价入股',
        '质押融资' => '质押融资',
        '其他'     => '其他',
    ];
}

if (!function_exists('storage_unlink')) {
    function storage_unlink($path, $disk = null): bool
    {
        $storage = \Illuminate\Support\Facades\Storage::disk($disk);
        if ($storage->exists($path)) {
            return $storage->delete($path);
        }
        return false;
    }
}

if (!function_exists('admin_upload_dir')) {
    function admin_upload_dir($dir = null): string
    {
        $dir = $dir ?: config('admin.upload.directory.file');
        return $dir . '/' . date('Ym');
    }
}

if (!function_exists('admin_store')) {
    function admin_store(\Illuminate\Http\UploadedFile $file, $path = null): string
    {
        $path = admin_upload_dir($path);
        return $file->storeAs($path, sprintf('%s.%s',
            \Illuminate\Support\Str::random(40),
            $file->getClientOriginalExtension()
        ), config('admin.upload.disk'));
    }
}

if (!function_exists('admin_storage_unlink')) {
    function admin_storage_unlink($path): string
    {
        return storage_unlink($path, config('admin.upload.disk'));
    }
}

if (!function_exists('file_preview_url')) {
    function file_preview_url($path, $name = null, $action = 'download'): string
    {
        $token = \App\Services\JWT\JWTService::previewToken([
            md5($path) => $path,
            'name'     => $name ?: '',
        ]);
        $param = [md5($path), $action, 'token' => $token];
        return admin_route('files.preview', $param);
    }
}

if (!function_exists('file_custom_preview_url')) {
    function file_custom_preview_url($path, $name, $action = 'download'): string
    {
        if ($name) {
            $name = $name . '.' . path_info($path, PATHINFO_EXTENSION);
        }
        return file_preview_url($path, $name, $action);
    }
}
if (!function_exists('valid_download_filename')) {
    function valid_download_filename($filename, $path = null): string
    {
        if ($filename) {
            $filename = strtr($filename, ['/' => '／', '\\' => '＼', '?' => '？', '*' => '×', '"' => '“', ':' => '：']);
            if ($path && !strstr($filename, '.')) {
                if ($ext = pathinfo($path, PATHINFO_EXTENSION)) {
                    $filename = $filename . '.' . $ext;
                }
            }
        }
        return $filename ?: '';
    }
}

if (!function_exists('setting_image_url')) {
    function setting_image_url($slug, $default = '')
    {
        return \App\Services\DocumentService::getInstance()->settingImageUrl($slug, $default);
    }
}

if (!function_exists('excel_import_date')) {
    function excel_import_date($date)
    {
        if ($date) {
            if (is_numeric($date)) {
                return date('Y-m-d', ($date - 25569) * 24 * 3600);
            }
            return \Illuminate\Support\Carbon::parse($date)->toDateString();
        }
        return null;
    }
}

if (!function_exists('url_add_query')) {
    function url_add_query($url, array $query): string
    {
        if (parse_url($url, PHP_URL_QUERY)) {
            return $url . '&' . http_build_query($query);
        }
        return $url . '?' . http_build_query($query);
    }
}
